<template>
  <div>
    <el-card class="box-card">
      <!-- 添加品牌按钮 -->
      <el-button type="primary" size="default" icon="Plus" @click="addTrademark"
        >添加品牌</el-button
      >
      <!-- 表格组件：展示数据列表 -->
      <el-table style="margin: 10px 0" border :data="trademarkArr">
        <el-table-column
          label="序号"
          width="80px"
          align="center"
          type="index"
        ></el-table-column>
        <el-table-column label="品牌名称" prop="tmName"></el-table-column>
        <el-table-column label="品牌LOGO">
          <template #="{ row }">
            <img :src="row.logoUrl" style="width: 100px; height: 100px" />
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #="{ row }">
            <el-button
              type="warning"
              size="small"
              icon="Edit"
              @click="updateTrademark(row)"
            ></el-button>
            <el-popconfirm
              :title="`确定删除${row.tmName}`"
              width="200px"
              icon="delete"
              @confirm="deleteTrademark(row.id)"
            >
              <template #reference>
                <el-button
                  type="danger"
                  size="small"
                  icon="Delete"
                  @click=""
                ></el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页器组件 -->
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[3, 5, 7, 9]"
        :background="true"
        layout="prev, pager, next, jumper, ->, sizes, total"
        :total="total"
        @current-change="getHasTrademark"
        @size-change="getHasTrademark"
      />
    </el-card>

    <el-dialog
      v-model="dialogFormVisible"
      :title="trademarkParams.id ? '修改品牌' : '添加品牌'"
    >
      <el-form
        style="width: 80%"
        :model="trademarkParams"
        :rules="rules"
        ref="formRef"
      >
        <el-form-item label="品牌名称" label-width="100px" prop="tmName">
          <el-input
            v-model="trademarkParams.tmName"
            placeholder="请输入品牌名称"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="品牌LOGO" label-width="100px" prop="logoUrl">
          <el-upload
            class="avatar-uploader"
            action="/api/admin/product/fileUpload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img
              class="avatar"
              v-if="trademarkParams.logoUrl"
              :src="trademarkParams.logoUrl"
            />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="primary" size="default" @click="cancel"
          >取消</el-button
        >
        <el-button type="primary" size="default" @click="confirm"
          >确定</el-button
        >
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { nextTick, onMounted, reactive, ref } from "vue";
import {
  reqHasTrademark,
  reqAddOrUpdateTrademark,
  reqDeleteTrademark,
} from "@/api/product/trademark";
import type {
  Records,
  TradeMarkResponseData,
  TradeMark,
} from "@/api/product/trademark/type";
import { ElMessage, type UploadProps } from "element-plus";
// 当前页码
const currentPage = ref<number>(1);
// 每页数据量
const pageSize = ref<number>(3);
// 存储已有品牌的总数
const total = ref<number>(0);
// 存储已有品牌的数据
const trademarkArr = ref<Records>([]);
// 控制对话框的显示与隐藏
const dialogFormVisible = ref<boolean>(false);
// 收集新增品牌的数据
const trademarkParams = reactive<TradeMark>({ tmName: "", logoUrl: "" });
// 获取el-form组件实例
const formRef = ref();
// 分页查询
const getHasTrademark = async (pager = 1) => {
  currentPage.value = pager;
  const result: TradeMarkResponseData = await reqHasTrademark(
    currentPage.value,
    pageSize.value,
  );
  total.value = result.data.total;
  trademarkArr.value = result.data.records.filter(
    (item) =>
      item.logoUrl !== "" &&
      item.logoUrl !==
        "39.98.123.211/group1/M00/03/D9/rBHu8mHmKC6AQ-j2AAAb72A3EO0942.jpg",
  );
};
// 组件挂载完毕发默认请求
onMounted(() => {
  getHasTrademark();
});
// 添加品牌按钮的回调
const addTrademark = () => {
  // 清空表单数据
  trademarkParams.id = 0;
  trademarkParams.tmName = "";
  trademarkParams.logoUrl = "";
  // 显示对话框
  dialogFormVisible.value = true;
  // 清除校验提示信息

  // 可选链写法
  // formRef.value?.clearValidate('tmName');
  // formRef.value?.clearValidate('logoUrl');

  // nextTick钩子函数，组件挂载完毕之后执行
  nextTick(() => {
    formRef.value.clearValidate("tmName");
    formRef.value.clearValidate("logoUrl");
  });
};
// 修改品牌按钮的回调
const updateTrademark = async (row: TradeMark) => {
  // 对话框显示
  dialogFormVisible.value = true;

  // 清除校验提示信息
  nextTick(() => {
    formRef.value.clearValidate("tmName");
    formRef.value.clearValidate("logoUrl");
  });

  // 收集数据
  Object.assign(trademarkParams, row);
};
// 删除品牌按钮确认的回调
const deleteTrademark = async (id: number) => {
  // 发起删除已有品牌的请求
  const result = await reqDeleteTrademark(id);
  if (result.code === 200) {
    // 删除成功提示信息
    ElMessage({
      type: "success",
      message: "删除品牌成功",
    });
    // 如果当前页只有一条数据，就到上一页，否则留在当前页
    getHasTrademark(
      trademarkArr.value.length > 1 ? currentPage.value : currentPage.value - 1,
    );
  } else {
    // 删除失败提示信息
    ElMessage({
      type: "error",
      message: "删除品牌失败",
    });
  }
};
// 对话框底部取消按钮
const cancel = () => {
  dialogFormVisible.value = false;
};
// 对话框底部确认按钮
const confirm = async () => {
  // 在发请求之前，要对于整个表单进行校验
  await formRef.value.validate();
  const result: any = await reqAddOrUpdateTrademark(trademarkParams);
  if (result.code === 200) {
    // 关闭对话框
    dialogFormVisible.value = false;
    // 弹出提示信息
    ElMessage({
      type: "success",
      message: trademarkParams.id ? "修改品牌成功" : "添加品牌成功",
    });
    // 刷新列表
    getHasTrademark(trademarkParams.id ? currentPage.value : 1);
  } else {
    // 关闭对话框
    dialogFormVisible.value = false;
    // 弹出提示信息
    ElMessage({
      type: "error",
      message: trademarkParams.id ? "修改品牌失败" : "添加品牌失败",
    });
  }
  dialogFormVisible.value = false;
};
// 上传图片之前触发的钩子函数
const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  // 上传文件之前可以约束上传文件的类型和大小
  const fileType = ["image/png", "image/jpeg", "image/gif"];
  if (fileType.includes(rawFile.type)) {
    if (rawFile.size / 1024 / 1024 < 4) {
      return true;
    } else {
      ElMessage({
        type: "error",
        message: "上传文件大小应该小于4M",
      });
    }
  } else {
    ElMessage({
      type: "error",
      message: "上传文件类型必须为PNG、JPG、GIT",
    });
  }
};
// 图片上传成功触发的钩子函数
const handleAvatarSuccess: UploadProps["onSuccess"] = (response) => {
  trademarkParams.logoUrl = response.data;
  // 图片上传成功，清除校验提示信息
  formRef.value.clearValidate("logoUrl");
};
// 品牌自定校验规则
const validatorTmName = (_rule: any, value: any, callback: any) => {
  // 当表单元素触发blur的时候，会触发此方法
  // 自定义校验规则
  if (value.trim().length >= 2) {
    callback();
  } else {
    callback(new Error("品牌名称不能少于2个字符"));
  }
};
// 品牌LOGO图片的自定义校验规则方法
const validatorLogoUrl = (_rule: any, value: any, callback: any) => {
  if (value) {
    callback();
  } else {
    callback(new Error("请上传品牌LOGO图片"));
  }
};
// 表单校验规则对象
const rules = {
  tmName: [{ required: true, trigger: "blur", validator: validatorTmName }],
  logoUrl: [{ required: true, validator: validatorLogoUrl }],
};
</script>

<style scoped lang="scss">
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
